<template>
  <div class="content">
    <div class="header">当即将滚动到列表底部时，自动加载更多数据</div>
    <!-- 滚动内容区域代码 -->
    <div class="container" ref="scroll">
      <div class="item" v-for="(item, index) in list" :key="index">
        {{ item.id }}
      </div>
      <div class="more" v-if="isLoad">{{ msg }}</div>
      <!-- <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">1</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">1</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div>
      <div class="item">3</div> -->
    </div>
  </div>
</template>

<script>
/* 思路： 要获取滚动区域的高度 监听页面滚动距离顶部的距离 */
export default {
  data() {
    return {
      isLoad: true,
      msg: "",
      list: [],
    };
  },
  created() {
    for (var i = 0; i < 15; i++) {
      this.list.push({
        id: i,
      });
    }
  },
  methods: {
    onScroll() {
      // 获取可滚动容器的高度
      let innerHeight = this.$el.clientHeight;

      // 获取屏幕尺寸高度
      let outerHeight = document.documentElement.clientHeight;

      // 可滚动容器超出当前窗口显示范围的高度
      let scrollTop = document.documentElement.scrollTop;

      // 避免切换数据时读取到异常高度
      if (scrollTop == 0) {
        innerHeight = 100000;
      }

      // scrollTop在页面滚动时为0，开始滚动后，慢慢增加，滚动到页面底部时，出现 innerHeight<  (outerHeight+scrollTop)的请况表示接近底部

      console.log(innerHeight + " " + outerHeight + " " + scrollTop);
      if (this.isLoad) {
        console.log(1);
        if (innerHeight <= outerHeight + scrollTop) {
          // 加载更多操作
          this.msg = "加载更多...";
          setTimeout(() => {
            for (var i = 0; i < 10; i++) {
              // 更新数据，下拉添加数据
              this.list.push({
                id: i,
              });
            }
          }, 2000);
        }
      }
    },
  },
  mounted() {
    // 开启滚动事件
    window.addEventListener("scroll", this.onScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScroll);
  },
};
</script>

<style>
* {
  margin: 0;
  padding: 0;
}
.header {
  position: fixed;
  width: 100%;
  margin-bottom: 10px;
  padding: 5px 0 5px 0;
  height: 50px;
  line-height: 50px;
  text-align: center;
  background: #ffffff;
  border-bottom: 1px solid #ccc;
}

.container {
  padding-top: 55px;
}

.item {
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-top: 1px solid #ccc;
}

.item:first-child {
  border: none;
}

.more {
  text-align: center;
  font-size: 20px;
  color: #ccc;
}
</style>
